package com.kehutong.payfees.admin;

import com.kehutong.common.DeptService;
import com.kehutong.common.PageUtils;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.receipt.PayBillManage;
import com.kehutong.payfees.entity.receipt.ReceiptStatistics;
import com.kehutong.payfees.service.receipt.PayManageServiceImpl;
import com.kehutong.payfees.util.PdfUtil;
import org.coraframework.authz.HasPermission;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.util.Objects;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @program: kht
 * @description: 缴费管理
 * @author: joneron
 * @create: 2021/5/28
 **/
@MvcAction
@ReqMapping("/admin/crm/charge/payment")
public class PayManageController {

    private static final Logger logger = LoggerFactory.getLogger(PayManageController.class);

    @Inject
    PayManageServiceImpl paymentBillService;

    @Inject
    FileUrlConfig fileUrlConfig;

    @Inject
    DeptService deptService;

    @ReqMapping("/page")
    @HasPermission("crm:charge:payment:view")
    public Object page(JSONObject jsonObject) {
        return paymentBillService.findPage(jsonObject);
    }

    @ReqMapping("/list")
    @HasPermission("crm:charge:payment:view")
    public Object list(JSONObject jsonObject) {
        return paymentBillService.findList(jsonObject);
    }


    @Bean(newInstance=true, copy=true)
    @HasPermission("crm:charge:payment:edit")
    @ReqMapping("/save")
    public Object save(PayBillManage entity, Token token) throws Exception {

        //查询小区是否已存在模板
        JSONObject jsonO = new JSONObject();

        for (int i = 0; i < entity.getCommunityList().size() ; i++) {
            jsonO.put("communityList",entity.getCommunityList().get(i));
            List<PayBillManage> listObj = paymentBillService.findList(jsonO);
            if(null != listObj && listObj.size() > 0){
                return Result.error(0, "该小区模板已经存在，请先检查！");
            }
        }

        if(StringUtil.isEmpty(entity.getSealImgId()) || entity.getCommunityList().size() == 0 || StringUtil.isEmpty(entity.getRemark())){
            return Result.error(0, "有必填项目没有填，请先检查！");
        }

        entity.setCreateName(token.getUsername());
        //上传的签章图片
        String fileImg = fileUrlConfig.getFile(entity.getSealImgId());

        PdfUtil pdfUtil = new PdfUtil();
        //保持时生成PDF文件保存到文件服务器
        byte[] pdf = pdfUtil.execute(pdfUtil.dataGenera(fileImg,entity.getPayBillName(),"payBill",entity.getRemark()));

        String pdfName = System.currentTimeMillis()+".pdf";

        File file = new File(pdfName);

        FileOutputStream outputFileStream = new FileOutputStream(file);
        outputFileStream.write(pdf);
        outputFileStream.close();

        JSONObject jsonObject =  fileUrlConfig.sendFile(file, http->{ });

        entity.setFileId(jsonObject.getJSONObject("data").getString("id"));

        List<String> departList = token.getDepartments();
        if(Objects.isEmpty(departList)){
            logger.error("用户{}数据异常，部门为空！",token.getUsername());
        }

        DeptDTO deptDTO = deptService.getDept(departList.get(0));
        entity.setDepartmentNo(deptDTO.getDepartmentNo());
        entity.setDepartmentNos(deptDTO.getDepartmentNos());
        entity.setDepartmentName(deptDTO.getDepartmentName());

        //文件上传成功后自动删除
        if (file.exists() && file.isFile() && file.delete() == true) {
            logger.info("{}本地文件已经删除!",pdfName);
        }

        return paymentBillService.save(entity);
    }

    @Bean(copy=true)
    @HasPermission("crm:charge:payment:edit")
    @ReqMapping("/update")
    public Object update(PayBillManage entity) {

        return paymentBillService.update(entity);
    }

    @HasPermission("crm:charge:payment:edit")
    @ReqMapping("/delete")
    public Object delete(PayBillManage entity) {

        return paymentBillService.deleteById(entity.getId());
    }

    @ReqMapping("/setStatus")
    @HasPermission("crm:charge:payment:edit")
    public Object setStatus(PayBillManage entity) {
        entity.setStatus(!entity.isStatus());
        paymentBillService.update(entity);
        return Result.success();
    }

    @ReqMapping("/get")
    public Object get(PayBillManage entity) {

        return Result.success(entity);
    }

    /**
     * 统计功能
     */
    @ReqMapping("/statistPage")
    @HasPermission("crm:charge:payment:view")
    public Object receiptStat(JSONObject jsonObject,Token token) throws Exception {

        List<ReceiptStatistics> listObj = paymentBillService.groupData(jsonObject,token);

        return PageUtils.buildPage(jsonObject,listObj);
    }

    @ReqMapping("/payPage")
    @HasPermission("crm:charge:payment:view")
    public Object payPage(JSONObject jsonObject) {

        return paymentBillService.findPayPage(jsonObject);
    }

}
